package cn.tedu.voice.system.service.impl;

import cn.tedu.voice.system.ex.ServiceException;
import cn.tedu.voice.system.mapper.LoginMapper;
import cn.tedu.voice.system.mvc.ServiceCode;
import cn.tedu.voice.system.pojo.dto.UserLoginDTO;
import cn.tedu.voice.system.pojo.entitly.User;
import cn.tedu.voice.system.pojo.vo.UserVO;
import cn.tedu.voice.system.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * 处理用户登录的实现类
 *
 * @author java@ccl.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public void addNew(UserLoginDTO userLoginDTO) {
        // 检查用户名是否已经被占用
        String username = userLoginDTO.getUsername();
        int countByUsername = loginMapper.countByUsername(username);
        if (countByUsername > 0) {
            throw new ServiceException("添加失败，名称已被占用!", ServiceCode.ERR_CONFLICT);
        }
        User user = new User();
        BeanUtils.copyProperties(userLoginDTO, user);
        log.debug("添加用户,参数：{}", user);
        int rows = loginMapper.insert(userLoginDTO);
        if (rows != 1) {
            throw new ServiceException("添加失败，服务器忙，请稍后尝试！", ServiceCode.ERR_INSERT);
        }
    }


    @Override
    public UserVO login(HttpSession session,UserLoginDTO userLoginDTO) {
        UserVO login = loginMapper.login(userLoginDTO.getUsername());
        if (login == null){
            throw new ServiceException("登录失败，用户不存在！", ServiceCode.ERR_CONFLICT);
        }else if (!login.getPassword().equals(userLoginDTO.getPassword())){
            throw new ServiceException("登录失败，密码错误！", ServiceCode.ERR_SELECT);
        }
        session.setAttribute("user",login);
        return login;
    }
}
